import './index.less'
import {Row, Col, Popover, Button, Modal, message} from 'antd'
import { WeaTools, WeaRichText, WeaLocaleProvider, WeaDialog, WeaInputSearch} from 'ecCom'
import * as SignUtil from "../../../workflowPublic/util/signUtil";
import { convertSpecialChar, realLength } from '../../util/signUtil';
import UserPhraseEdit from './../wf-user-phrase-edit/index'
import UserPhraseEditStore from './../../stores/UserPhraseEdit'
import trim from "lodash/trim";
import Content from './Content';
const getLabel = WeaLocaleProvider.getLabel;
const userPhraseEditStore = new UserPhraseEditStore();
export default class Main extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            signContent: "",
            showPhrases: false,
            editPhrases: false,
            showModal: false,
            disabled:true,
            searchValue:"",
            phrasesDatas: [],//有条件筛选的短语
            phrasesDatas_back: [],//备用的短语
        };
    }

    componentDidMount() {
      this.loadPhrasesDatas();
    }

    
    //加载流程短语
    loadPhrasesDatas() {
      const { phrasesDatas_back }  = this.state;
      WeaTools.callApi('/api/workflow/reqform/getPhrases', 'POST').then(data => {
          let phrasesDatas = data.phrasesDatas;
          if (this.state.searchValue) {
              phrasesDatas = phrasesDatas_back.filter(item => (item.short.includes(this.state.searchValue) || item.desc.includes(this.state.searchValue)));
          }
          this.setState({ phrasesDatas: data.phrasesDatas, phrasesDatas_back: data.phrasesDatas, searchValue: "" });
          this.refs.phrasesRef && this.refs.phrasesRef.setState({ phrasesDatas: data.phrasesDatas, phrasesDatas_back: data.phrasesDatas, searchValue: "" });
      });
    }
    changeEditPhrases = (bool) => {
      this.setState({editPhrases: bool});
    }
    clickPhrases = (index,data) => {
      const appendPhrasesValue = data && data[index].desc;
      this.setState({showPhrases: false, editPhrases: false});
      this.refs.WeaRichText.insertHTML(convertSpecialChar(`${appendPhrasesValue}<br>`), 'last');
      WeaTools.callApi('/api/workflow/userDefaultSetting/updateFrequency', 'POST', {id:data[index].id,groupid:data[index].groupid})
    }
    
    componentWillReceiveProps(nextProps) {
        if(!nextProps.visible) {
            this.setState({'signContent':''});
        }
    }

    shouldComponentUpdate(nextProps, nextState) {
        return this.props.visible !== nextProps.visible
            ||this.props.loading !== nextProps.loading
            || this.state.signContent !== nextState.signContent
            || this.state.showPhrases !== nextState.showPhrases
            || this.state.editPhrases !== nextState.editPhrases
            || this.state.disabled !== nextState.disabled;
    }

    render() {
        const {visible, loading = false} = this.props;
        const {signContent, showPhrases, editPhrases, phrasesDatas} = this.state;
        let ckConfig = {};
        ckConfig.toolbar = [];
        ckConfig.height = 260;
        // ckConfig.height = 190;
        ckConfig.removePlugins  = 'resize';
      
        return (
            <WeaDialog ecId={`${this && this.props && this.props.ecId || ''}_WeaDialog@l67dk2`} parentClassName="wf-batch-submit"
                       visible={visible}
                       icon={'icon-coms-workflow'}
                       iconBgcolor='#0079DE'
                       title={getLabel('383485', '填写签字意见')}
                       onCancel={this.cancelEvent}
                       buttons={this.getBottomButtons()}
                       style={{width: 740, height: 345}}
                       loading={loading}
                       layout={jQuery('#container')[0]}
                       moreBtn={{datas:this.getMoreButtons(),collectParams:{favname:getLabel('383485', '填写签字意见'), favouritetype:'2',importantlevel:1}}}
            >
                <div className="wf-batch-submit-area">
                    <div className="wf-batch-submit-btn-part">
                        <Popover ecId={`${this && this.props && this.props.ecId || ''}_Popover@v44y4x`} overlayClassName="wf-phrases-popover"
                                 placement="bottomLeft"
                                 trigger="click"
                                 content={
                                  <Content ecId={`${this && this.props && this.props.ecId || ''}_Content@0k7pea`} 
                                    ref={ref => {this.refs.phrasesRef = ref}} 
                                    richRef = {this.refs.WeaRichText}
                                    userPhraseEditStore = {userPhraseEditStore} 
                                    changeEditPhrases ={this.changeEditPhrases} 
                                    clickPhrases = {this.clickPhrases}
                                  />
                                }
                                 visible={showPhrases}
                                 zIndex='1050'
                                 onVisibleChange={v => {
                                     this.setState({ showPhrases: !showPhrases });//, editPhrases: false
                                     if (!v) {//隐藏的时候，就去掉搜索条件
                                         this.setState({ phrasesDatas: this.state.phrasesDatas_back, searchValue:"" });
                                         this.refs.phrasesRef && this.refs.phrasesRef.setState({ searchValue:"" });
                                         this.loadPhrasesDatas();
                                     }
                                 }}>
                            <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@owoxln`} disabled={this.state.disabled}>
                                <i className="icon-coms-Advice"/>
                                <span>{getLabel(22409, '常用批示语')}</span>
                            </Button>
                        </Popover>
                    </div>
                    <div>
                        <WeaRichText ecId={`${this && this.props && this.props.ecId || ''}_WeaRichText@c4ais4`} ckConfig={ckConfig} value={signContent} ref={'WeaRichText'} onChange={this.changeSignContent}  onStatusChange={this.doStatusChange}/>
                    </div>
                    <UserPhraseEdit ecId={`${this && this.props && this.props.ecId || ''}_UserPhraseEdit@tbltfz`}
                        store={userPhraseEditStore}
                        visiable={this.state.editPhrases}
                        saveCallBack={(phraseInfo) => {
                            this.setState({ editPhrases: false });
                            this.setState({ phraseInfo: [...this.state.phrasesDatas, phraseInfo] });
                            this.loadPhrasesDatas()
                        }}
                        setVisiable={(val) => {
                            this.setState({ editPhrases: val })
                        }}
                    />
                </div>
            </WeaDialog>
        );
    }

    getBottomButtons() {
        const {loading = false,onSubmitText=''} = this.props;
        let btnArr = [];
        btnArr.push(<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@38r9so@submit`} type="primary" size="large" disabled={loading}
                            onClick={this.submitEvent}>{onSubmitText===''?getLabel(725, '提交'):onSubmitText}</Button>);
        return btnArr;
    }


    getMoreButtons(){
        const {onSubmitText='',iconClassName=''} = this.props;
        let datas =  [{
            key: '1',
            disabled: false,
            icon: <i className={iconClassName===''?'icon-workflow-Right-menu-Approval':iconClassName} />,
            content: onSubmitText===''?getLabel(725, '提交'):onSubmitText,
            onClick: key => this.submitEvent(),
        }];
        return datas;
    }

    

    changeSignContent = (value) => {
        this.setState({signContent: value});
    }

    doStatusChange=(status)=>{
        if (status === "ready") {
            this.setState({disabled:false})
        }
    }

  

    submitEvent = () =>  {
        this.props.onSubmit(this.state.signContent || "");
    }

    cancelEvent = () =>  {
        this.setState({signContent: ""});
        this.props.onCancel();
    }
}